/*
 * @Description: 
 * @Autor: luojie
 * @Date: 2021-07-05 17:13:51
 * @LastEditors: luojie
 * @LastEditTime: 2021-08-13 15:24:05
 */
import { getData } from "../api";
import CryptoJS from 'crypto-js'
/**
 * @description: 
 * @param {*} fn
 * @return {*}
 */
export function scanCode(_params) {
  uni.removeStorageSync('isolationPersonnel')
  uni.removeStorageSync('personInfo')
  let { fn } = _params;
  let dictionaries = {
    1: '0',
    2: '0',
    3: '88',
    4: '55',
    5: '66',
    6: '1',
    7: '9',
    8: '89',
    9: '90',
  }
  uni.setStorage({ key: 'isolationPersonnel', data: {} });
  wx.scanCode({
    success: async (res) => {
      let result = res.result;
      let personKey = '',
        QRCodeType = '';
      var oneYardPass = new RegExp(/^[a-zA-z]+-/).test(result);
      // console.log('扫码结果===', res);
      if (result.indexOf('options=') != -1) {
        personKey = res.result.split('options=')[1].split('&')[0];
        QRCodeType = '深i您';
      } else if (oneYardPass) {
        personKey = result;
        QRCodeType = '一码通';
      } else {
        uni.showToast({
          title: `请正确扫码`,
          icon: 'none',
          duration: 3000
        });
        return
      }
      uni.setStorage({ key: 'QRCodeType', data: QRCodeType });  // 二维码类型
      uni.setStorage({ key: 'personKey', data: personKey });    // 二维码值
      let targetUser = {}
      // 一码通后端暂时无法获取到数据，所以一码通不调接口
      if (QRCodeType == '深i您') {
        targetUser = await getData('getUser', 'get', { personKey: personKey });
      }
      if (QRCodeType == '一码通') {
        // personKey = 'CHN-C81466702'
        let data = await getData('codeInfo', 'get', { code: personKey });
        targetUser =  {
          age: getAge(data.birthdate),  // 年龄
          cardNumber: data.cardNumber,     // 证件号码  一码通码面值
          id_type: data.cardType, // 证件类型
          id_code: data.cardNumber, // 身份证号码，无则取一码通码面值
          //性别 深i您 0 女 1男   一码通 1男 2女
          sex : data.gender==2?0:data.gender,  
          name: data.name, //姓名
          nationality: data.nationalityCn, // 国籍
          phone: data.phoneEncode, // 手机号
          uid: data.uid, 
        }
      }
      let params = {
        name: targetUser.name,
        cardId: targetUser.id_code,
        cardType: QRCodeType == '一码通' ? targetUser.id_type : dictionaries[targetUser.id_type],
        daSourceId: personKey,
        daSource:QRCodeType == '一码通' ? '03': '02'
      };
      targetUser.daSourceId =  params.daSourceId;
      targetUser.daSource = params.daSource
      let personInfo = await getData('personInfo', 'get', {
        daSource: params.daSource,
        daSourceId: params.daSourceId
      })
      personInfo = personInfo && personInfo[0]
      targetUser.personInfo = personInfo || {};
      uni.setStorage({ key: 'personInfo', data: personInfo });
      uni.setStorage({ key: 'isolationPersonnel', data: targetUser });
     
      fn && fn({
        QRCodeType,
        personKey,
        targetUser,
        params
      });
    },
  })
}

// 是保洁or消杀
function isBaojOrXiaos(type){
  return type=='clean'||type=='disinfect';
}
// 扫码：消杀、保洁和巡检使用
export function scanOrderCode(_params) {
  let { fn, type } = _params;
  uni.setStorage({ key: 'QRCodeInfo', data: {} });
  wx.scanCode({
    success: async (res) => {
      let result = res.result;
      // console.log('扫码结果====', res);
      if(result.indexOf('isolationHotelId')!=-1||(isBaojOrXiaos(type)&&result.indexOf('houseId')!=-1)){  // 保洁/消杀通过houseId判断
        let params = '';
        if(String(result).charCodeAt(0) == 65279){
          params = JSON.parse(result.substring(1,result.length));
        }else{
          params = JSON.parse(result);
        }
        fn && fn()
        uni.setStorage({ key: 'QRCodeInfo', data: params });
      }else{
        uni.showToast({
          title: `请正确扫码！`,
          icon: 'none',
          duration: 3000
        });
      }
    }
  })
}
// 扫码：一码通使用
export function scanOneYardPass(_params) {
  let { fn } = _params;
  wx.scanCode({
    success: async (res) => {
      let daSourceId = res.result;
      var oneYardPass = new RegExp(/^[a-zA-z]+-/).test(daSourceId);
      if(oneYardPass){
        let personInfo = await getData('codeInfo', 'get', { code:daSourceId });
        fn && fn({ 
          daSourceId,
          personInfo
        });
      }else{
        uni.showToast({
          title: `请扫一码通二维码！`,
          icon: 'none',
          duration: 3000
        });
      }
    }
  })
}

/**
 * @description 转base64编码
 * @param {*} str：传入的字符串
 * @return {*} 输出base64格式
 */
export function encode(str) {
  var c1, c2, c3;
  var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var i = 0, len = str.length, string = '';

  while (i < len) {
    c1 = str.charCodeAt(i++) & 0xff;
    if (i == len) {
      string += base64EncodeChars.charAt(c1 >> 2);
      string += base64EncodeChars.charAt((c1 & 0x3) << 4);
      string += "==";
      break;
    }
    c2 = str.charCodeAt(i++);
    if (i == len) {
      string += base64EncodeChars.charAt(c1 >> 2);
      string += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
      string += base64EncodeChars.charAt((c2 & 0xF) << 2);
      string += "=";
      break;
    }
    c3 = str.charCodeAt(i++);
    string += base64EncodeChars.charAt(c1 >> 2);
    string += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
    string += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
    string += base64EncodeChars.charAt(c3 & 0x3F)
  }
  return string
}

/**
 * @description 加密手机号（格式：手机号码:时间戳  -->  再转base64）
 * @param {*} phone
 * @return {*} 输出加密过的手机号码
 */
export function dealPhoneNum(phone) {
  const time = Date.parse(new Date());
  const composeText = `${phone}:${time}`;
  // return encode(composeText);
  return encrypt(composeText)
}

// AES加密方法
function encrypt(word){ 
  let keyStr = 'bmsk202107141800';
  var key  = CryptoJS.enc.Utf8.parse(keyStr);
  var srcs = CryptoJS.enc.Utf8.parse(word);
  var encrypted = CryptoJS.AES.encrypt(srcs, key, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
  return encrypted.toString();
}
// 解密方法
function decrypt(word){  
  let keyStr = 'bmsk202107141800';
  var key  = CryptoJS.enc.Utf8.parse(keyStr);
  var decrypt = CryptoJS.AES.decrypt(word, key, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
  return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}

/**
 * //翻译字典值
 * @param {JSON} dic 字典 
 * @param {string|number} value 值 
 * @returns 
 */
export const translateDic = (dic, value)=>{
  let data = dic.find(item => item.value == value)
  return data ? data.label : ''
}


/**
 * 节流：单位时间内保证出发一次
 */
export const throttle = (fn, delay) => {
	let timer = true;
	return function(args) {
		let that = this;
		let _args = arguments;
		if(!timer){
		   return false;
		}
		timer = false;
		setTimeout(() => {
			fn.apply(that, _args)
			timer = true;
		}, delay)
	}
}


export const getDicByType = (type)=>{
  let obj=uni.getStorageSync('alldic')
  return obj[type].children;
}

export function removeAllStorageSync(){
  uni.removeStorageSync('personalInfo');
  uni.removeStorageSync('dataFromUserBaseInfo');
  uni.removeStorageSync('QRCodeType');
  uni.removeStorageSync('personInfo');
  uni.removeStorageSync('isolationPersonnel');
  uni.removeStorageSync('telPhone');
  uni.removeStorageSync('shenAiNin');
  uni.removeStorageSync('reportType');
  uni.removeStorageSync('dataIsi');
  uni.removeStorageSync('dataPhq9');
  uni.removeStorageSync('dataGad7');
  uni.removeStorageSync('health');
  uni.removeStorageSync('healthInspectRes');
  uni.removeStorageSync('faceLastRecord');
  uni.removeStorageSync('cardId');
  uni.removeStorageSync('personKey');
  uni.removeStorageSync('token');
  uni.removeStorageSync('avatarUrl');
  uni.removeStorageSync('environSample');
  uni.removeStorageSync('observedInfo');
  uni.removeStorageSync('QRCodeInfo');
  uni.removeStorageSync('thisRoomNum');
}

export function getNowTime  () {
  let dateTime
  let yy = new Date().getFullYear()
  let mm = new Date().getMonth() + 1
  let dd = new Date().getDate()
  let hh = new Date().getHours()
  mm = mm<10?'0'+mm:mm;
  dd = dd<10?'0'+dd:dd;
  hh = hh<10?'0'+hh:hh;
  let mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes()
    :
    new Date().getMinutes()
  let ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds()
    :
    new Date().getSeconds()
  dateTime = yy + '-' + mm + '-' + dd + ' ' + hh + ':' + mf + ':' + ss
  console.log(dateTime)
  return dateTime
}

// 计算年龄 birthdate = 1996-05-07
function getAge(birthdate){
  var r = birthdate.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);     
  if(r==null)return null;     
  var d = new Date(r[1], r[3]-1, r[4]);     
  if(d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]){   
    var Y = new Date().getFullYear();
    return ((Y-r[1]));
  }   
  return null
}

// 根据环境值跳转不同页面
function judgeScene(scene){
  let scenes = ['1001','1011','1012','1013','1047','1048','1049']
  if(scenes.indexOf(scene)){
    uni.reLaunch({
      url: `/packageIsolate/pages/userBaseInfo/index`,
    });
    // login('19988886666').then(res=>{
      
    // })
  }
}